package cn.xo68.demo.controller;

import cn.xo68.boot.jwt.JwtTokenUtil;
import cn.xo68.core.crypto.EncryptAlgorithmEnums;
import cn.xo68.core.crypto.rsa.RsaEncryptHandleImpl;
import cn.xo68.core.security.Base64Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class HomeController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @GetMapping("/")
    public String index() throws Exception {
        KeyPair keyPair = RsaEncryptHandleImpl.generatorKeyPair(EncryptAlgorithmEnums.RSA_512);

        String publicKey= Base64Utils.encode(keyPair.getPublic().getEncoded());
        String privateKey=Base64Utils.encode(keyPair.getPrivate().getEncoded());
        log.info(" \r\n private: {} \r\n publice:{}",privateKey,publicKey);

        return privateKey+"\r\n"+publicKey;
    }

    @GetMapping("/create")
    public String createToken(@RequestParam(name = "userId") String userId,@RequestParam(name = "userName") String userName) throws UnsupportedEncodingException {
        Map<String,Object> vals= new HashMap<>();
        vals.put("role","admin,user");
        vals.put("com","xo68");
        return jwtTokenUtil.generateToken(userName,userId,0L,vals);
    }

    @GetMapping("/validate")
    public Object validateToken(@RequestParam(name = "token") String token){
        Map<String, Object> vals = jwtTokenUtil.getMapFromToken(token);
        log.info("vals: {}",vals);
        return vals;
    }
}
